﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using General;

namespace BrainCrusher
{
    public partial class Form1 : Form
    {
        private Client.Client cl;
        private List<User> users;
        private User curUsr;
        private object o = new object();
        private bool flag = false;
        public Form1()
        {
            InitializeComponent();
            ConnectClient();
            curUsr = new User();
            textBox1.Text = "jino01";
            textBox2.Text = "123";
        }

        private void SignIn(object sender, EventArgs e)
        {
            ConnectClient();
            try
            {
                if (cl.SignIn(new User(textBox1.Text, textBox2.Text)))
                {
                    MessageBox.Show("Авторизація пройшла успішно");
                    textBox2.Enabled = false;
                    textBox1.Enabled = false;
                    timer1.Enabled = true;
                    GetUpdates(sender, EventArgs.Empty);
                }
                else
                {
                    MessageBox.Show("Неправильний логін або пароль");
                }
            }
            catch (Exception ex)
            { MessageBox.Show(ex.Message); }
            dataGridView1.AutoResizeColumns();
        }

        private void SignOut(object sender, EventArgs e)
        {
            ConnectClient();
            try
            {
                if (cl.SignOut())
                {
                    MessageBox.Show("Деавторизація пройшла успішно");
                    textBox2.Enabled = true;
                    textBox1.Enabled = true;
                    timer1.Enabled = false;
                }
                else
                {
                    MessageBox.Show("Ви не авторизовані");
                }
            }
            catch (Exception ex)
            { MessageBox.Show(ex.Message); }
        }

        private void GetContentRecords(object sender, EventArgs e)
        {
            ConnectClient();
            try
            {
                dataGridView1.DataSource = cl.GetContentTable(int.Parse(textBox3.Text), int.Parse(textBox4.Text)).Tables[0].DefaultView;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void AddAnswer(object sender, EventArgs e)
        {
            listBox1.Items.Add(textBox6.Text);
        }

        private void SelectContent(object sender, EventArgs e)
        {
            ConnectClient();
            if (dataGridView1.SelectedRows.Count == 1)
            {
                try
                {
                    Content tmp = cl.GetContent((int)dataGridView1.SelectedRows[0].Cells["id"].Value);
                    listBox1.Items.Clear();
                    foreach (string str in tmp.m_answers)
                    {
                        listBox1.Items.Add(str);
                    }
                    textBox5.Text = tmp.m_question;
                    textBox7.Text = tmp.m_correct.ToString();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        private void AddContent(object sender, EventArgs e)
        {
            ConnectClient();
            string[] arr = new string[listBox1.Items.Count];
            for (int i = 0; i < listBox1.Items.Count; i++)
            {
                arr[i] = listBox1.Items[i].ToString();
            }
            int n = -1;
            if (!int.TryParse(textBox7.Text, out n))
            {
                MessageBox.Show("Виберіть правильну відповідь");
            }
            else
            {
                Content tmp = new Content(arr, textBox5.Text, n);
                try
                {
                    if (cl.AddContent(tmp))
                        MessageBox.Show("Додання контенту успішне");
                    else
                        MessageBox.Show("Помилка при доданні контенту");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    GetContentRecords(sender, EventArgs.Empty);
                }
            }
        }

        private void SelectAnswer(object sender, EventArgs e)
        {
            textBox7.Text = listBox1.SelectedIndex.ToString();
        }

        private void GetUpdates(object sender, EventArgs e)
        {
            ConnectClient();
            try
            {
                lock (o)
                {
                    if (cl.NewConnect())
                    {
                        listBox2.Items.Clear();
                        users = cl.ConnectedUsers;
                        foreach (User u in users)
                        {
                            listBox2.Items.Add(u.m_id);
                        }
                    }
                    if (cl.NewContent())
                    {
                        listBox3.Items.Clear();
                        Content cont = cl.GetCurrentContent();
                        richTextBox1.Text = cont.m_question;
                        foreach (string s in cont.m_answers)
                        {
                            listBox3.Items.Add(s);
                        }
                        if (flag)
                        {
                            MessageBox.Show(cl.GetAnswerUser());
                        }
                    }
                    User tmp = cl.CurrentUser;
                    if (curUsr.m_id != tmp.m_id ||
                        curUsr.m_psw != tmp.m_psw ||
                       curUsr.m_name != tmp.m_name ||
                       curUsr.m_email != tmp.m_email ||
                       curUsr.m_points != tmp.m_points ||
                        curUsr.m_admin != tmp.m_admin)
                    {
                        curUsr = cl.CurrentUser;
                        textBox16.Text = curUsr.m_points.ToString();
                        textBox15.Text = curUsr.m_id;
                        textBox14.Text = curUsr.m_psw;
                        textBox13.Text = curUsr.m_email;
                        textBox12.Text = curUsr.m_name;

                        if (curUsr.m_admin)
                            checkBox1.Checked = true;
                        else
                            checkBox1.Checked = false;
                    }
                    listView1.Items.Clear();
                    foreach (User u in cl.TopUsers)
                    {
                        ListViewItem t = new ListViewItem(u.m_id);
                        t.SubItems.Add(u.m_points.ToString());
                        t.SubItems.Add(u.m_name);
                        listView1.Items.Add(t);
                    }
                    flag = true;
                }
            }
            catch (Exception ex)
            { MessageBox.Show(ex.Message); }

        }

        private void GetConnectedUserInfo(object sender, EventArgs e)
        {
            ConnectClient();
            try
            {
                User tmp = users.Find(obj => obj.m_id == listBox2.Items[listBox2.SelectedIndex].ToString());
                MessageBox.Show("Логін : " + tmp.m_id + Environment.NewLine + "Кількість очок : " + tmp.m_points);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void SelectCorrectAnswer(object sender, EventArgs e)
        {
            ConnectClient();
            try
            {
                lock (o)
                {
                    if (cl.Answer(listBox3.SelectedIndex))
                        MessageBox.Show("Правильна відповідь");
                    else
                        MessageBox.Show("Неправильна відповідь");
                }
            }
            catch { }
        }

        private void UpdateContent(object sender, EventArgs e)
        {
            ConnectClient();
            if (dataGridView1.SelectedRows.Count == 1)
            {
                try
                {
                    Content tmp = cl.GetContent((int)dataGridView1.SelectedRows[0].Cells["id"].Value);
                    listBox1.Items.Clear();
                    foreach (string str in tmp.m_answers)
                    {
                        listBox1.Items.Add(str);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    GetContentRecords(sender, EventArgs.Empty);
                }
            }
        }

        private void ConnectClient()
        {
            try
            {
                if (cl == null || !cl.ClientConnected)
                    cl = new Client.Client();
            }
            catch { }
        }

        private void RegisterNewUser(object sender, EventArgs e)
        {
            ConnectClient();
            User tmp = new User();
            tmp.m_id = textBox8.Text;
            tmp.m_psw = textBox9.Text;
            tmp.m_email = textBox10.Text;
            tmp.m_name = textBox11.Text;

            try
            {
                if (cl.Register(tmp))
                    MessageBox.Show("Реєстрація успішна");
                else
                    MessageBox.Show("Реєстрація невдала");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void ChangeAccount(object sender, EventArgs e)
        {
            ConnectClient();
            User tmp = new User();
            tmp.m_psw = textBox14.Text;
            tmp.m_email = textBox13.Text;
            tmp.m_name = textBox12.Text;
            try
            {
                cl.CurrentUser = tmp;
                if (cl.EditAccount())
                    MessageBox.Show("Зміни збережено");
                else
                    MessageBox.Show("Не вдалося зберегти зміни");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void DeleteContent(object sender, EventArgs e)
        {
            ConnectClient();
            try
            {
                if (dataGridView1.SelectedRows.Count == 1)
                {
                    if (cl.DeleteContent((int)dataGridView1.SelectedRows[0].Cells["id"].Value))
                        MessageBox.Show("Контент видалено");
                    else
                        MessageBox.Show("Помилка при видаленні контенту");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                throw;
            }
            finally { GetContentRecords(sender, EventArgs.Empty); }

        }

        private void GetUserRecords(object sender, EventArgs e)
        {
            ConnectClient();
            try
            {
                dataGridView2.DataSource = cl.GetUsers(int.Parse(textBox17.Text), int.Parse(textBox18.Text)).Tables[0].DefaultView;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void SelectUserRecord(object sender, DataGridViewCellEventArgs e)
        {
            ConnectClient();
            if (dataGridView2.SelectedRows.Count == 1)
            {
                try
                {
                    User tmp = cl.GetUser((string)dataGridView2.SelectedRows[0].Cells["id"].Value);
                    textBox19.Text = tmp.m_id;
                    textBox20.Text = tmp.m_psw;
                    textBox21.Text = tmp.m_name;
                    textBox22.Text = tmp.m_email;
                    textBox23.Text = tmp.m_points.ToString();
                    if (tmp.m_admin)
                        checkBox2.Checked = true;
                    else
                        checkBox2.Checked = false;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }

        }

        private void DeleteUser(object sender, EventArgs e)
        {
            ConnectClient();
            try
            {
                if (dataGridView2.SelectedRows.Count == 1)
                {
                    if (cl.DeleteUser((string)dataGridView2.SelectedRows[0].Cells["id"].Value))
                        MessageBox.Show("Користувачі видалено");
                    else
                        MessageBox.Show("Помилка при видаленні користувача");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                throw;
            }
            finally
            {
                GetUserRecords(sender, EventArgs.Empty);
            }
        }

        private void UpdateUser(object sender, EventArgs e)
        {
            try
            {
                User tmp = new User();
                if (int.TryParse(textBox23.Text, out tmp.m_points))
                {
                    tmp.m_id = textBox19.Text;
                    tmp.m_psw = textBox20.Text;
                    tmp.m_name = textBox21.Text;
                    tmp.m_email = textBox22.Text;
                    if (checkBox2.Checked)
                        tmp.m_admin = true;
                    else
                        tmp.m_admin = false;
                    if (cl.EditUser(tmp, tmp.m_id))
                        MessageBox.Show("Запис користувача оновлена");
                    else
                        MessageBox.Show("Помилка оновлення запису користувача");
                }
                else { MessageBox.Show("Очки введені невірно"); }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                throw;
            }
            finally
            {
                GetUserRecords(sender, EventArgs.Empty);
            }

        }

        private void DeleteAnswer(object sender, EventArgs e)
        {
            try
            {
                listBox1.Items.RemoveAt(listBox1.SelectedIndex);
            }
            catch { }
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabControl1.SelectedIndex == 1 && !cl.Admin)
            {
                tabControl1.SelectedTab = tabPage1;
                MessageBox.Show("Ви не маєте адміністраторських прав");
            }
        }
    }
}
